<?php

namespace app\api\controller\user;

use app\api\controller\Controller;
use app\api\model\Setting as SettingModel;
use app\api\model\dealer\Setting as DealerSettingModel;
use app\api\model\dealer\User as DealerUserModel;
use app\api\model\Order as OrderModel;
use app\api\model\user\PointsLog as PointsLogModel;
use app\api\model\user as UserModel;

/**
 * 个人中心主页
 * Class Index
 * @package app\api\controller\user
 */
class Index extends Controller
{
    /* @var \app\api\model\User $user */
    private $user;

    private $dealer;
    private $setting;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        // 用户信息
        $this->user = $this->getUser();
        // 分销商用户信息
        $this->dealer = DealerUserModel::detail($this->user['user_id']);
        // 分销商设置
        $this->setting = SettingModel::getItem("store");
    }

    /**
     * 获取当前用户信息
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        // 订单总数
        $model = new OrderModel;
        return $this->renderSuccess([
            'userInfo' => $this->user,
            'orderCount' => [
                'payment' => $model->getCount($this->user['user_id'], 'payment'),
                'received' => $model->getCount($this->user['user_id'], 'received'),
                'comment' => $model->getCount($this->user['user_id'], 'comment'),
            ],
            'is_open_dealer' => DealerSettingModel::isOpen(),
            'is_dealer' => $this->isDealerUser(),
//            'is_share' => PointsLogModel::userIsShareToday($this->user['user_id']),
            'setting' => $this->setting
        ]);
    }

    /**
     * 当前用户是否为分销商
     * @return bool
     */
    private function isDealerUser()
    {
        return !!$this->dealer && !$this->dealer['is_delete'];
    }

    /**
     * 获取指定用户详情
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function details($user_id)
    {
        return $this->renderSuccess([
            'userInfo' => UserModel::detail($user_id)
        ]);
    }

}
